package cn.heycm.blog.common.web.filter;

import cn.heycm.blog.common.entity.constant.Constant;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.UUID;

/**
 * @author hey
 * @version 1.0
 * @since 2024/9/15 18:00
 */
@Component
public class TraceFilter extends OncePerRequestFilter implements Ordered {
    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            MDC.put(Constant.TRACE_ID, createTraceId());
            filterChain.doFilter(request, response);
        } finally {
            MDC.remove(Constant.TRACE_ID);
        }
    }

    private String createTraceId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
